﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Collections.ObjectModel;
using System.Xml.Linq;
using System.Windows.Browser;

namespace SkyDriveConnector
{
    public partial class MainPage : UserControl
    {
        TreeViewItem selectedItem;
        object currentItemCollection;
        private static string folderpath;
        private string AuthToken;
        
        public MainPage()
        {
            InitializeComponent();

           
            gridResponseMessages.ItemsSource = App.Logger.ResponseMessages;

            HtmlPage.RegisterScriptableObject("SkdClientScripts", this);
          
        }

        [ScriptableMember]
        public void GetToken(string token)
        {
            

            if (token == null)
            {
                //MessageBox.Show("token is null");
            }
            else
            {
                AuthToken = token;
                LoadNodeItems<SkyDriveObject>((TreeViewItem)skydriveTreeView.Items[0], "");
              
            }
        }

        


        private void btnLoadFiles_Click(object sender, RoutedEventArgs e)
        {

            //AuthToken = txtToken.Text;
            LoadNodeItems<SkyDriveObject>((TreeViewItem)skydriveTreeView.Items[0], "");
            

        }

        private void LoadNodeItems<T>(ItemsControl treeviewItem, string itempath)
        {
            //GenericViewModel<T> viewmodel = new GenericViewModel<T>(txtToken.Text);
            GenericViewModel<T> viewmodel = new GenericViewModel<T>(AuthToken);
            treeviewItem.ItemsSource = viewmodel.ItemsCollection;
            currentItemCollection = viewmodel.ItemsCollection;
            
            viewmodel.GetItems(itempath);
        }


        private void LoadChildItems(ItemsControl currentItem, string itempath)
        {
            selectedItem.IsExpanded = true;
            selectedItem.Items.Clear();
            TreeViewItem childObjects = new TreeViewItem();
            childObjects.ItemTemplate = selectedItem.ItemTemplate;
            childObjects.Style = (Style)Resources["TreeViewItemStyle1"];
            childObjects.IsExpanded = true;
            selectedItem.Items.Add(childObjects);
            LoadNodeItems<SkyDriveObject>(childObjects, itempath);
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            
            
        }

        private void skyDriveTreeview_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            selectedItem = skydriveTreeView.ContainerFromItem(((TreeView)sender).SelectedItem);
            LoadItems();
            

        }


        private void LoadItems()
        {
            if (selectedItem != null && selectedItem.Header != null && selectedItem.Header.GetType() == typeof(string))
            {
                LoadNodeItems<SkyDriveObject>(selectedItem, "");
            }
            else if (selectedItem.Header != null && (((SkyDriveObject)selectedItem.Header).type != "file" &&
                ((SkyDriveObject)selectedItem.Header).type != "photo"))
            {
                //folderpath += ((SkyDriveObject)selectedItem.Header).name + "/";
                ((SkyDriveObject)selectedItem.Header).icon = "images/folderopen.png";
                LoadChildItems(selectedItem, ((SkyDriveObject)selectedItem.Header).upload_location);

            }
            else if (selectedItem.Header != null && (((SkyDriveObject)selectedItem.Header).type == "file" ||
                ((SkyDriveObject)selectedItem.Header).type == "photo") && ((SkyDriveObject)selectedItem.Header).name != "Empty")
            {
                GenericViewModel<FieldValue> viewmodel = new GenericViewModel<FieldValue>();
                PropertiesList.ItemsSource = viewmodel.ItemsCollection;
                //gridResponseMessages.ItemsSource = TraceLog.ResponseMessages;
                viewmodel.GetSingleItem(((SkyDriveObject)selectedItem.Header).id);

            }

        }

        private void btnNewItem_Click(object sender, RoutedEventArgs e)
        {
            HideContextMenu();
            string folderid;
            GenericViewModel<SkyDriveObject> viewmodel = new GenericViewModel<SkyDriveObject>(AuthToken);
            viewmodel.ItemsCollection = (ObservableCollection<SkyDriveObject>) currentItemCollection;

            if (selectedItem != null && selectedItem.Header.GetType() == typeof(SkyDriveObject) &&  (SkyDriveObject)selectedItem.Header != null)
            {
                folderpath = "";
                GetParentFolderItem(selectedItem);
                folderpath += ((SkyDriveObject)selectedItem.Header).name + "/";
                viewmodel.SharePointPath = folderpath;
                viewmodel.ItemPath = ((SkyDriveObject)selectedItem.Header).upload_location;
                folderid = ((SkyDriveObject)selectedItem.Header).id;

            }
            else
            {
                viewmodel.ItemPath = "";
                folderid = "me/skydrive";

            }

            OpenFileDialog openfiledialog1 = new OpenFileDialog();
            //FileStream fs;
            bool? userclickedok = openfiledialog1.ShowDialog();
            if (userclickedok == true)
            {
                //fs = openfiledialog1.File.OpenRead();
                viewmodel.AddNewItem(folderid, openfiledialog1.File.OpenRead(), openfiledialog1.File.Name);

            }
        }

        private void btnDeleteItem_Click(object sender, RoutedEventArgs e)
        {
            HideContextMenu();
            MessageBoxResult confirmDelete = MessageBox.Show(string.Format("Are you sure you want to delete {0}?", ((SkyDriveObject)selectedItem.Header).name),
                "Confirm Delete", MessageBoxButton.OKCancel);


            if (confirmDelete == MessageBoxResult.Cancel)
            {
                return;
            }



            GenericViewModel<SkyDriveObject> viewmodel = new GenericViewModel<SkyDriveObject>(AuthToken);
            //viewmodel.ItemsCollection = (ObservableCollection<SkyDriveObject>)currentItemCollection;
            string deleteItemPath = ((SkyDriveObject)selectedItem.Header).id;

            selectedItem = GetParentTreeViewItem(selectedItem);
            //selectedItem.IsSelected = true;
            viewmodel.ItemsCollection = (ObservableCollection<SkyDriveObject>) selectedItem.ItemsSource;
           

            if (selectedItem != null && selectedItem.Parent.GetType() != typeof(TreeView))
                viewmodel.ItemPath = ((SkyDriveObject)((TreeViewItem)selectedItem.Parent).Header).upload_location;
           
            viewmodel.DeleteItem(deleteItemPath);

            foreach (var item in PropertiesList.Items)
            {
                if (((FieldValue)item).FieldDisplayName == "ID")
                {
                    GenericViewModel<FieldValue> deleteItemObject = new GenericViewModel<FieldValue>();
                    deleteItemObject.DeleteSharePointItem(((FieldValue)item).Value);

                }
            }
        }

        private static TreeViewItem GetParentTreeViewItem(DependencyObject item)
        {
            if (item != null)
            {
                DependencyObject parent = VisualTreeHelper.GetParent(item);
                TreeViewItem parentTreeViewItem = parent as TreeViewItem;
                return (parentTreeViewItem != null) ? parentTreeViewItem : GetParentTreeViewItem(parent);
            }
            return null;
        }

        private void btnNewFolder_Click(object sender, RoutedEventArgs e)
        {
            HideContextMenu();


            if (((SkyDriveObject)selectedItem.Header).type == "file")
                return;

            CreateFolderWindow cw = new CreateFolderWindow();
            cw.Closed += new EventHandler(CreateFolderWindow_Closed);
            cw.Show();

        }

        private void CreateFolderWindow_Closed(object sender, EventArgs e)
        {
            CreateFolderWindow cw = (CreateFolderWindow)sender;
            string currentFolderName = "";
            if (cw.DialogResult == true && cw.txtFolderName.Text != string.Empty)
            {
                string folderid;
                GenericViewModel<SkyDriveObject> viewmodel = new GenericViewModel<SkyDriveObject>(AuthToken);
                viewmodel.ItemsCollection = (ObservableCollection<SkyDriveObject>)currentItemCollection;

                if (selectedItem != null && selectedItem.Header.GetType() == typeof(SkyDriveObject) && (SkyDriveObject)selectedItem.Header != null)
                {

                    viewmodel.ItemPath = ((SkyDriveObject)selectedItem.Header).upload_location;
                    folderid = ((SkyDriveObject)selectedItem.Header).id;
                    currentFolderName = ((SkyDriveObject)selectedItem.Header).name;

                }
                else
                {
                    viewmodel.ItemPath = "";
                    folderid = "me/skydrive";

                }

                folderpath = "";
                GetParentFolderItem(selectedItem);
                folderpath += currentFolderName + "/";
                viewmodel.CreateFolder(folderid, cw.txtFolderName.Text, cw.txtFolderDescription.Text, folderpath, folderid);

            }
             
        }

        private static TreeViewItem GetParentFolderItem(DependencyObject item)
        {
            if (item != null)
            {
                DependencyObject parent = VisualTreeHelper.GetParent(item);
                TreeViewItem parentTreeViewItem = parent as TreeViewItem;
                if (parentTreeViewItem != null && parentTreeViewItem.Header != null && parentTreeViewItem.Header.GetType() == typeof(SkyDriveObject))
                {
                    folderpath = string.Format("{1}/{0}", folderpath, ((SkyDriveObject)parentTreeViewItem.Header).name);
                }
                GetParentFolderItem(parent);
                //return (parentTreeViewItem != null) ? parentTreeViewItem : GetParentFolderItem(parent);
            }

            return null;
        }
      



        private void btnImportItem_Click(object sender, RoutedEventArgs e)
        {
            HideContextMenu();
            MessageBoxResult confirmDelete = MessageBox.Show(string.Format("Are you sure you want to Import {0}?", ((SkyDriveObject)selectedItem.Header).name),
                "Confirm Import", MessageBoxButton.OKCancel);


            if (confirmDelete == MessageBoxResult.Cancel)
            {
                return;
            }

            GenericViewModel<SharePointModel> viewmodel = new GenericViewModel<SharePointModel>();
            folderpath = "";
            GetParentFolderItem(selectedItem);
            if (selectedItem != null && selectedItem.Header != null && selectedItem.Header.GetType() == typeof(SkyDriveObject))
            {
                if (((SkyDriveObject)selectedItem.Header).type == "folder" || ((SkyDriveObject)selectedItem.Header).type == "album")
                {

                    viewmodel.CreateSharePointFolder(folderpath, ((SkyDriveObject)selectedItem.Header).name, ((SkyDriveObject)selectedItem.Header).id);

                    
                }
                else
                {
                    viewmodel.AddNewItem(folderpath,(SkyDriveObject)selectedItem.Header);
                }

            }
  
        }




        private void btnDebugInfo_Click(object sender, RoutedEventArgs e)
        {

            HideContextMenu();
            if (gridResponseMessages.Visibility == System.Windows.Visibility.Collapsed)
            {
                LayoutRoot.RowDefinitions[1].Height = new GridLength(300);
                LayoutRoot.RowDefinitions[0].Height = new GridLength(500);
                gridResponseMessages.Visibility = System.Windows.Visibility.Visible;

            }

            else
            {
                
                LayoutRoot.RowDefinitions[1].Height = new GridLength(0);
                LayoutRoot.RowDefinitions[0].Height = new GridLength(LayoutRoot.ActualHeight);
                gridResponseMessages.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void btnLoadSkyDrive_Click(object sender, RoutedEventArgs e)
        {
          
            try
            {
                AuthToken = (string)HtmlPage.Window.Invoke("GetAccessToken");
                //MessageBox.Show(AuthToken);
            }
            catch (Exception ex)
            {

                //MessageBox.Show(ex.ToString());
            }

            LoadNodeItems<SkyDriveObject>((TreeViewItem)skydriveTreeView.Items[0], "");
        }

        private void btnSyncItems_Click(object sender, RoutedEventArgs e)
        {
            HideContextMenu();
            MessageBoxResult confirmDelete;

            if (selectedItem.Header.GetType() == typeof(SkyDriveObject))
            {
                confirmDelete = MessageBox.Show(string.Format("Are you sure you want to Sync {0}?", ((SkyDriveObject)selectedItem.Header).name),
                   "Confirm Sync", MessageBoxButton.OKCancel);

            }
            else
            {
                confirmDelete = MessageBox.Show(string.Format("Are you sure you want to Sync {0}?", selectedItem.Header),
                  "Confirm Sync", MessageBoxButton.OKCancel);
            }

            if (confirmDelete == MessageBoxResult.Cancel)
            {
                return;
            }

            ItemCollection items=null;
            if (selectedItem.Header.GetType() == typeof(string))
                items = selectedItem.Items;
            else if(selectedItem.Header.GetType() == typeof(SkyDriveObject))
                items = ((TreeViewItem)selectedItem.Items[0]).Items;

            foreach (SkyDriveObject item in items)
            {
                GenericViewModel<SharePointModel> viewmodel = new GenericViewModel<SharePointModel>();
                folderpath = "";
                GetParentFolderItem(selectedItem);

                if (selectedItem.Header.GetType() == typeof(SkyDriveObject))
                    folderpath = folderpath + ((SkyDriveObject)selectedItem.Header).name + "/";

                if (item != null && item.GetType() == typeof(SkyDriveObject))
                {
                    if (item.type == "folder" || item.type == "album")
                    {

                        viewmodel.CreateSharePointFolder(folderpath, item.name, item.id);


                    }
                    else
                    {

                        viewmodel.AddNewItem(folderpath, item);
                    }

                }
  

            }
        }

        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            HideContextMenu();
            LoadItems();
        }

        private void btnSortNameAsc_Click(object sender, RoutedEventArgs e)
        {
            HideContextMenu();

            if (selectedItem.Header.GetType() == typeof(string))
                selectedItem.ItemsSource = selectedItem.Items.SortByObjectKey("Asc", item => ((SkyDriveObject)item).name);
            else if (selectedItem.Header.GetType() == typeof(SkyDriveObject) && selectedItem.Items.Count > 0)
                ((TreeViewItem)selectedItem.Items[0]).ItemsSource = ((TreeViewItem)selectedItem.Items[0]).Items.SortByObjectKey("Asc", item => ((SkyDriveObject)item).name);
           
        }

        private void btnSortNameDesc_Click(object sender, RoutedEventArgs e)
        {
            HideContextMenu();

            if (selectedItem.Header.GetType() == typeof(string))
                selectedItem.ItemsSource = selectedItem.Items.SortByObjectKey("Desc", item => ((SkyDriveObject)item).name);
            else if (selectedItem.Header.GetType() == typeof(SkyDriveObject) && selectedItem.Items.Count > 0)
                ((TreeViewItem)selectedItem.Items[0]).ItemsSource = ((TreeViewItem)selectedItem.Items[0]).Items.SortByObjectKey("Desc", item => ((SkyDriveObject)item).name);
           
        }

        private void btnSortDateAsc_Click(object sender, RoutedEventArgs e)
        {
            HideContextMenu();

            if (selectedItem.Header.GetType() == typeof(string))
                selectedItem.ItemsSource = selectedItem.Items.SortByObjectKey("Asc", item => ((SkyDriveObject)item).updated_time);
            else if (selectedItem.Header.GetType() == typeof(SkyDriveObject) && selectedItem.Items.Count > 0)
                ((TreeViewItem)selectedItem.Items[0]).ItemsSource = ((TreeViewItem)selectedItem.Items[0]).Items.SortByObjectKey("Asc", item => ((SkyDriveObject)item).updated_time);
           
        }

        private void btnSortDateDesc_Click(object sender, RoutedEventArgs e)
        {
            HideContextMenu();

            if (selectedItem.Header.GetType() == typeof(string))
                selectedItem.ItemsSource = selectedItem.Items.SortByObjectKey("Desc", item => ((SkyDriveObject)item).updated_time);
            else if (selectedItem.Header.GetType() == typeof(SkyDriveObject) && selectedItem.Items.Count > 0)
                ((TreeViewItem)selectedItem.Items[0]).ItemsSource = ((TreeViewItem)selectedItem.Items[0]).Items.SortByObjectKey("Desc", item => ((SkyDriveObject)item).updated_time);
           
        }

        private void TreeViewItems_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void TreeViewItems_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {

            if (DropDownMenu.Visibility == System.Windows.Visibility.Collapsed)
            {
                Canvas.SetTop(DropDownMenu, e.GetPosition(skydriveTreeView).Y);
                Canvas.SetLeft(DropDownMenu, e.GetPosition(skydriveTreeView).X + 40);
                DropDownMenu.Visibility = Visibility.Visible;
                Canvas.SetZIndex(DropDownMenu, 100);
            }
            else
            {
                DropDownMenu.Visibility = System.Windows.Visibility.Collapsed;
            }
            

        }

      

        private void HideContextMenu()
        {
            if ((ListBoxItem)DropDownMenu.SelectedItem != null)
                ((ListBoxItem)DropDownMenu.SelectedItem).IsSelected = false;

            DropDownMenu.Visibility = Visibility.Collapsed;
            Canvas.SetZIndex(DropDownMenu, -1);

        }

        private void GridSplitter_LayoutUpdated(object sender, EventArgs e)
        {
          
            skydriveTreeView.Width = LayoutRoot.ColumnDefinitions[0].ActualWidth;
            skydriveTreeView.Height = LayoutRoot.RowDefinitions[0].ActualHeight;

        }

    

      
        
    }
}
